<template>
  <div class="mt-1">
    <van-form>
      <h4 style="margin: 0 0 0.4rem 1rem; color: gray">
        当前产区:{{ this.$store.getters.productionLine }}
      </h4>
      <!-- <sub-text-title></sub-text-title> -->
      <van-field
        v-model="code"
        clearable
        label="拍码"
        ref="pmfocus"
        @focus="stopKeyborad"
        placeholder="请输入拍码"
      />
      <!--  <van-field
        readonly
        clickable
        :value="rollid"
        label="膜卷号"
        placeholder="点击选择"
        @click="rollPicker = true"
      />
      <van-popup v-model="rollPicker" position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="rollAdjustConfirm"
          @cancel="rollPicker = false"
        />
      </van-popup> -->
      <ag-grid-vue
        id="itxst"
        style="width: 100%; height: 58vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row type="flex" gutter="10" justify="center">
        <van-col span="6">
          <van-button block type="info" class="mt-1" @click="submit"
            >退回</van-button
          ></van-col
        >
        <van-col span="7">
          <van-button type="warning" class="mt-1" block @click="Backonce"
            >单独修改</van-button
          ></van-col
        >
      </van-row>
    </van-form>
    <OverValue
      v-model="saveValueVisible"
      @saveNum="saveNum"
      @canCel="canCel"
      :Asure="sureWIP"
      :ShowData="NumAdjustData"
    />
    <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { Picker } from "vant";
import { CODE_LENGTH } from "../../config";
import { AgGrid } from "../../mixins/AgGrid";
import { parseQRCode, toast } from "../../utils/common";
import { getFedData, EndPost } from "../../api/feeding";
import OverValue from "../../components/OverValue";
// import SubTextTitle from "../../components/subtextTitle.vue";
export default {
  name: "WIP",
  components: { AgGridVue, OverValue, [Picker.name]: Picker },
  mixins: [AgGrid],
  data() {
    return {
      code: "",
      savenum: "",
      sureWIP: "",
      //rollid: "",
      //rollPicker: false,
      //sureWIP: false,
      saveValueVisible: false,
      columnDefs: [
        { headerName: "物料号", field: "ProductId", width: 90 },
        { headerName: "物料名称", field: "ProductName", width: 125 },
        {
          headerName: "数量",
          field: "Num",
          width: 80,
        },
        {
          headerName: "退回数量",
          field: "backNum",
          width: 90,
        },
        { headerName: "膜卷号", field: "DeviceCode", width: 90 },
        { headerName: "操作时间", field: "CreatedOn", width: 145 },
      ],
      rowData: [],
      readyData: [],
      rowPallenNoNum: [],
      NumAdjustData: [], //传给数组的数据
      //columns: [],
      rollData: [],
      rollDataA: [],
      selectedData: [],
    };
  },
  watch: {
    code(val) {
      if (val.length > CODE_LENGTH) {
        let res = parseQRCode(val);
        console.log(res);
        if (res) {
          //this.columns = [];
          if (/^HUABL/.test(res.palletNo)) {
            toast("Blending投料不能退回");
          } else {
            this.findPat(res.palletNo);
          }

          //this.GetWindNumber(res.materialCode, res.palletNo);
          //console.log(result);
          /* console.log(this.rowData);
          if (this.rollData.length == 0) {
            console.log("111"); */
          //this.findPat(res.palletNo);
          /* } else {
            console.log("2332");
            //this.findPat(res.palletNo);
          } */
        } else {
          this.playMusic();
          toast("无法识别");
        }
      }
      this.code = "";
      this.NumAdjustData = [];
      this.$refs.pmfocus.focus();
    },
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    //从外界添加数据
    async findPat(palletNo) {
      if (!this.rowData.find((it) => it.UniqueId === palletNo)) {
        let productionline = this.$store.getters.productionLine;
        let res = await getFedData(
          productionline,
          palletNo,
          this.$store.getters.WarehouseId
        );
        console.log(res);
        if (res && res.Status == 200 && res.Data.length > 0) {
          //将数据放到组件数组中
          console.log(res.Data);
          /*   let Number = null;
          res.Data.map((it) => {
            Number += it.Num;
          }); */
          //如果一条数据，默认弹出
          if (res.Data.length == 1) {
            this.NumAdjustData.push({
              OutStorageBillDetailId: res.Data[0].OutStorageBillDetailId,
              ProductId: res.Data[0].ProductId,
              ProductName: res.Data[0].ProductName,
              UniqueId: res.Data[0].UniqueId,
              Num: res.Data[0].Num,
              DeviceCode: res.Data[0].DeviceCode,
              CreatedOn: res.Data[0].CreatedOn,
            });
            console.log(this.NumAdjustData);
            this.readyDat = JSON.parse(JSON.stringify(this.NumAdjustData));
            this.addData(this.readyDat);
            //展示组件
            this.saveValueVisible = true;
          } else if (res.Data.length > 1) {
            //多条数据，选择投料
            /*  this.rDat = ;
            console.log(this.readyDat); */
            this.addData(JSON.parse(JSON.stringify(res.Data)));
          }
        } else if (res.Status != 200) {
          this.playMusic();
          toast(res.Msg);
        } else if (res.Data.length == 0) {
          this.playMusic();
          toast("此拍没有投料数据");
        }
      } else {
        this.playMusic();
        toast("此拍已被录入");
      }
    },
    //调数据组件
    saveNum(savevalue, sure) {
      this.savenum = savevalue;
      this.sureWIP = sure;
      /*       if (this.sureWIP == true) {
        this.addData(this.readyDat);
        this.sureWIP = "";
      } */
      if (this.selectedData.length == 0) {
        this.rowData[this.rowData.length - 1].backNum = Number(this.savenum);
        console.log(this.rowData);
        this.gridApi.refreshCells();
        this.savenum = "";
        this.$refs.pmfocus.focus();
      } else {
        this.selectedData[0].backNum = Number(this.savenum);
        this.gridApi.updateRowData({ updata: this.selectedData[0] });
        this.savenum = "";
        this.$refs.pmfocus.focus();
      }
    },
    canCel(sure) {
      this.sureWIP = sure;
      this.saveValueVisible = false;
      this.savenum = "";
      this.$refs.pmfocus.focus();
    },
    //遍历之后加数据
    addData(Data) {
      let _this = this;
      Data.map((item) => {
        _this.rowData.push({
          ProductId: item.ProductId,
          UniqueId: item.UniqueId,
          Num: item.Num,
          ProductName: item.ProductName,
          OutStorageBillDetailId: item.OutStorageBillDetailId,
          DeviceCode: item.DeviceCode,
          CreatedOn: item.CreatedOn,
        });
      });
    },
    //将表单里的数据归类
    getPalletNoNum() {
      let _that = this;
      this.gridApi.forEachNode((node) => {
        _that.rowPallenNoNum.push({
          OutStorageBillDetailId: node.data.OutStorageBillDetailId,
          UniqueId: node.data.UniqueId,
          Num: node.data.backNum,
        });
      });
    },
    //提交，退回操作
    async submit() {
      /*     OutStorageBillDetailId: detailid,
    UniqueId: unique,
    Num: num */
      this.getPalletNoNum();
      console.log(this.rowPallenNoNum);
      if (this.rowData.length > 0) {
        let num2 = await EndPost(this.rowPallenNoNum);
        if (num2.Status == 200) {
          this.rowPallenNoNum = [];
          this.rowData = [];
          toast(num2.Msg);
        } else {
          this.playMusic();
          toast(num2.Msg);
          this.rowPallenNoNum = [];
        }
      } else {
        this.playMusic();
        toast("请先扫码");
      }
      this.$refs.pmfocus.focus();
      /* let selectedData = this.gridApi.getSelectedRows();
      if (selectedData.length != 0) {
        console.log(selectedData);
        if (selectedData[0].backNum == 0) {
          let number = await EndPost(
            selectedData[0].OutStorageBillDeatilId,
            selectedData[0].UniqueId,
            selectedData[0].Number
          );
          if (number.Status == 200) {
                         console.log(number);
            //删除数组中的某个值
            let a = this.gridApi.updateRowData({ remove: selectedData });
            //删除rowData内此值
            let selectIndex = this.rowData.indexOf(a.remove[0]);
            console.log(selectIndex);
            this.rowData.splice(selectIndex - 1, 1); 
            
          } else {
            toast(number.Msg);
          }
        } else {
          let num2 = await EndPost(
            selectedData[0].OutStorageBillDeatilId,
            selectedData[0].UniqueId,
            Number(this.savenum)
          );
          if (num2.Status == 200) {
            toast(num2.Msg);
          } else {
            toast(num2.Msg);
          }
        }
      } else {
        toast("未选择需要退回行");
      } */
    },
    //选择确认
    //选择膜卷号
    rollAdjustConfirm(val, index) {
      this.rollid = val.match(/\w+(?=-)/g)[0];
      //this.rollindex = index;
      this.rollPicker = false;
      console.log(this.rollData, index);
      this.rollDataA = this.rollData[index];
      console.log(this.rollDataA);
      this.findPat(val.match(/(?<=-)\w+/g)[0]);
    },
    //单独退回
    async Backonce() {
      this.NumAdjustData = [];
      this.selectedData = this.gridApi.getSelectedRows();
      console.log(this.selectedData[0]);
      if (this.selectedData[0]) {
        this.saveValueVisible = true;
        console.log(this.saveValueVisible);
        this.NumAdjustData.push(this.selectedData[0]);
        console.log(this.NumAdjustData);
        /*   //if (this.sureWIP == true) {
        let NeedDate = [
          {
            OutStorageBillDetailId: selectedData[0].OutStorageBillDetailId,
            UniqueId: selectedData[0].UniqueId,
            Num: Number(this.savenum),
          },
        ];
        let number = await EndPost(NeedDate);
        if (number.Status == 200) {
          //删除数组中的某个值
          let a = this.gridApi.updateRowData({ remove: selectedData });
          //删除rowData内此值
          let selectIndex = this.rowData.indexOf(a.remove[0]);
          this.rowData.splice(selectIndex - 1, 1);
          this.saveValueVisible = false;
          this.sureWIP = false;
          this.NumAdjustData = [];
        } else {
          this.playMusic();
          toast(number.Msg);
        }
        console.log(number);
        //} */
      } else {
        this.playMusic();
        toast("未选择需要退回行");
      }
      this.$refs.pmfocus.focus();
    },
    /*     //获取膜卷号
    async GetWindNumber(material, palletNO) {
      let res = await GetWindNumber(
        this.$store.getters.productionLine,
        palletNO,
        "",
        material
      );
      if (res.Status == 200 && res.Data != null) {
        let _this = this;
        this.rollData = JSON.parse(JSON.stringify(res.Data));
        console.log(this.rollData);
        res.Data.map((it) => {
          _this.columns.push(`${it.WindingNumber}-${it.UniqueId}`);
        });
      } else {
        toast(res.Msg);
      }
      if (this.rollData.length == 0) {
        console.log("111");
        this.findPat(palletNO);
      } else {
        console.log("2332");
        //this.findPat(res.palletNo);
      }

      console.log(res);
    }, */
  },
  mounted() {
    this.$refs.pmfocus.focus();
    document.onkeydown = function (e) {
      if (e.code == "Enter") {
        e.preventDefault();
      }
    };
  },
};
</script>